import md5 from 'md5'
import { uploadFunc } from '@utils/polyv-upload'
/* 初始化保利威视上传视频插件 */
export function uploadVideo(polyvNumber, callBack, params = {}) {
  return new Promise((resolve, reject) => {
    /* uploadFunc()*/
    var upload = null
    let data = polyvApi(polyvNumber)
    let obj = {
      uploadButtton: 'upload',
      hash: data.hash,
      readToken: data.readToken,
      sign: data.sign,
      ts: data.ts,
      component: 'uploadList',
      userid: data.userid,
      fileTypeLimit: 'avi,mpg,mp4,flv,wmv,mov,3gp,mkv,mp3,wav,m4v,webm',
      uploadSuccess: function(fileData) {
        callBack(fileData, upload)
        // 上传成功回调
        upload.closeWrap()
      },
      uploadFail: function(err) {
        console.log('上传失败，失败原因：', err.data)
      }
    }
    //根据params传参，增加/更改obj中的参数
    if (Object.keys(params).length > 0) {
      for (let key in params) {
        obj[key] = params[key]
      }
    }
    upload = new PolyvUpload(obj)
    // 定时更新时间戳
    upload.timer = setInterval(function() {
      let newData = polyvApi(polyvNumber)
      upload.update(newData)
    }, 2 * 60 * 1000)
    return resolve(upload)
  })
}
function polyvApi(polyvNumber) {
  let userid = polyvNumber.polyvUserId
  let secretkey = polyvNumber.polyvSecretKey
  let writeToken = polyvNumber.polyvWriteToken
  let readToken = polyvNumber.polyvReadToken

  let ts = new Date().getTime()
  let hash = md5(ts + writeToken)
  let sign = md5(secretkey + ts)
  let data = {
    ts,
    hash,
    sign,
    userid,
    secretkey,
    writeToken,
    readToken
  }
  return data
}
